package com.sky.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.mapper.EmployeeMapper;
import com.sky.po.EmployeePO;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.repository.EmployeeRepository;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeRepository employeeRepository;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 员工登录
     * @param employeeLoginDTO
     * @return
     */
    public EmployeePO login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();
        System.out.println(passwordEncoder.encode(password));

        //1、根据用户名查询数据库中的数据
        EmployeePO employeePO = employeeRepository.selectOne(new LambdaQueryWrapper<EmployeePO>()
                .eq(EmployeePO::getUsername,username)
                .last("limit 1"));
        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (ObjectUtil.isNull(employeePO)) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        System.out.println(passwordEncoder.encode(password));
        //密码比对
        if (!passwordEncoder.matches(password, employeePO.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employeePO.getStatus().equals(StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employeePO;
    }

    /**
     * 新增员工
     * @param employeeDTO
     * @return
     */
//    @AutoFill(OperationType.INSERT)
    @Override
    public Boolean newEmployee(EmployeeDTO employeeDTO) {
        EmployeePO employeePO = EmployeeMapper.INSTANCE.DTOConvertPO(employeeDTO);
        //设置账号的状态,默认正常状态(1:正常,0:异常)
        employeePO.setStatus(StatusConstant.ENABLE);
        //设置密码,默认123456
        employeePO.setPassword(passwordEncoder.encode("123456"));
        return employeeRepository.insert(employeePO)!=0;
    }

    /**
     * 按条件分页查询员工
     * @param source
     * @return
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO source) {
//        PageHelper.startPage(source.getPage(),source.getPageSize());
//        if(StrUtil.isBlank(source.getName())){
//            source.setName("");
//        }
//        List<EmployeePO> employees = employeeRepository.selectList(new LambdaQueryWrapper<EmployeePO>()
//                .like(EmployeePO::getName, source.getName()));
//        //隐藏密码
//        employees.forEach(e->e.setPassword(""));
//        PageInfo<EmployeePO> pageInfo = new PageInfo<>(employees);

        if(StrUtil.isBlank(source.getName())){
            source.setName("");
        }
        Page<EmployeePO> page = new Page<>(source.getPage(), source.getPageSize());
        employeeRepository.selectPage(page,new LambdaQueryWrapper<EmployeePO>()
                .like(EmployeePO::getName, source.getName()));
        page.getRecords().forEach(s->s.setPassword(""));
        return new PageResult(page.getTotal(), page.getRecords());
    }

    /**
     * 启用/禁用用户
     * @param status
     * @param id
     */
    @Override
    public Boolean startOrStop(Integer status, Long id) {
        //TODO:后续如果有前端源码可以将接口路径更改一下
        EmployeePO employeePO = employeeRepository.selectById(id);
        if(employeePO.getStatus().equals(StatusConstant.ENABLE)){
            //禁用员工
            employeePO.setStatus(StatusConstant.DISABLE);
            return employeeRepository.updateById(employeePO)>0;
        }
        //启用员工
        employeePO.setStatus(StatusConstant.ENABLE);
        return employeeRepository.updateById(employeePO)>0;
    }

    /**
     * 根据id查询用户信息
     * @param id
     * @return
     */
    @Override
    public EmployeeDTO getById(Long id) {
        EmployeePO employeePO = employeeRepository.selectById(id);
        System.out.println("employeePO:"+employeePO);
        return EmployeeMapper.INSTANCE.POConvertDTO(employeePO);
    }

    /**
     * 更新员工信息
     * @param source
     * @return
     */
    @Override
    public Boolean update(EmployeeDTO source) {
        EmployeePO employeePO = EmployeeMapper.INSTANCE.DTOConvertPO(source);
        employeePO.setUpdateUser(BaseContext.getCurrentId());
        employeePO.setUpdateTime(LocalDateTime.now());
        return employeeRepository.updateById(employeePO)>0;
    }

}
